use thiserror::Error;

/// 应用程序错误类型定义
#[derive(Error, Debug)]
pub enum AppError {
    #[error("数据库错误: {0}")]
    Database(#[from] sqlx::Error),
    
    #[error("迁移错误: {0}")]
    Migration(#[from] sqlx::migrate::MigrateError),
    
    #[error("设备错误: {0}")]
    Device(String),
    
    #[error("网络错误: {0}")]
    Network(#[from] tauri_plugin_http::reqwest::Error),
    
    #[error("序列化错误: {0}")]
    Serialization(#[from] serde_json::Error),
    
    #[error("加密错误: {0}")]
    Crypto(String),
    
    #[error("任务错误: {0}")]
    Task(String),
    
    #[error("配置错误: {0}")]
    Config(String),
    
    #[error("IO错误: {0}")]
    Io(#[from] std::io::Error),
    
    #[error("验证错误: {0}")]
    Validation(String),
    
    #[error("未找到: {0}")]
    NotFound(String),
    
    #[error("权限错误: {0}")]
    Permission(String),
    
    #[error("超时错误: {0}")]
    Timeout(String),
    
    #[error("其他错误: {0}")]
    Other(String),
}

/// 应用程序结果类型别名
pub type Result<T> = std::result::Result<T, AppError>;

impl From<AppError> for String {
    fn from(error: AppError) -> Self {
        error.to_string()
    }
}

/// 为Tauri命令提供错误转换
impl serde::Serialize for AppError {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: serde::ser::Serializer,
    {
        serializer.serialize_str(self.to_string().as_ref())
    }
}